# -*- coding: utf-8 -*-
# @Time : 2023/03/29 14:40
# @Author : ricky
# @File : main.py
# @Software: vscode
import wx
from main_frame import MainFrame
import os
import platform
import sys
import traceback
from subprocess import Popen
from cajparser import CAJParser
import threading

EXPORT_IGNORE = (".DS_Store")

class Main(MainFrame):
    def __init__(self, parent):
        MainFrame.__init__(self, parent)
        app_name = wx.GetApp().GetAppName()
        if app_name != 'run' and platform.system().lower().startswith('win'):
            icon = wx.Icon(f'{app_name}.exe', wx.BITMAP_TYPE_ICO)
            self.SetIcon(icon)
        self.m_dir_picker_caj.GetPickerCtrl().SetLabel('选择目录')
        self.m_dir_picker_pdf.GetPickerCtrl().SetLabel('选择目录')
        self.m_dir_picker_caj.SetInternalMargin(self.m_dir_picker_caj.GetInternalMargin() * 2)
        self.m_dir_picker_pdf.SetInternalMargin(self.m_dir_picker_pdf.GetInternalMargin() * 2)
        self.Centre()

    def show_message(self, message):
        '''统一显示对话框

        根据传入对话框内容显示对话框

        Args:
            message (str): 对话框内容
        '''
        wx.MessageDialog(None, message, u"操作提醒", wx.OK).ShowModal()

    # 实现转换事件
    def OnClickEventConvert(self, event):
        cajdir = self.m_dir_picker_caj.GetPath()
        if len(cajdir) == 0:
            self.show_message(u"请选择CAJ文件目录")
            return
        pdfdir = self.m_dir_picker_pdf.GetPath()
        if len(pdfdir) == 0:
            self.show_message(u"请选择PDF文件目录")
            return
        t = threading.Thread(target=self.convert,
                                 args=(cajdir, pdfdir))
        t.start()
       
    # 转换文件
    def convert(self, cajdir, pdfdir):
        wx.CallAfter(self.m_text_log.Clear)
        wx.CallAfter(self.m_btn_convert.Disable)
        wx.CallAfter(self.m_btn_convert.SetLabelText, '转换中...')
        caj_files = os.listdir(cajdir)
        counter = 0
        for caj_file_name in caj_files:
            caj_file_path = os.path.join(cajdir, caj_file_name)
            if not os.path.isfile(caj_file_path) or not str(caj_file_name).endswith(".caj"):
                continue
            pdf_file_path = os.path.join(pdfdir, str(caj_file_name).replace(".caj", ".pdf"))
            if os.path.exists(pdf_file_path):
                os.remove(pdf_file_path)
            try:
                caj = CAJParser(caj_file_path)
                caj.convert(pdf_file_path)
                counter+=1
            except Exception as e:
                print('traceback.format_exc():\n%s' % traceback.format_exc())
                wx.CallAfter(self.m_text_log.AppendText, '%s【%s】\n' % (caj_file_name, str(e)))
                self.m_text_log.ShowPosition(self.m_text_log.GetLastPosition())
        wx.CallAfter(self.m_btn_convert.Enable)
        wx.CallAfter(self.m_btn_convert.SetLabelText, '开始转换')
        self.show_message(u"转换结束，共转换{}个文件".format(counter))
        
        
    # 实现打开程序目录事件
    def OnClickEventOpenTempDir(self, event):
        if hasattr(sys, '_MEIPASS'):
            exepath = sys._MEIPASS
        else:
            exepath = os.path.dirname(os.path.realpath(sys.argv[0]))
        try:
            os.startfile(exepath)
        except:
            Popen(['open', exepath])

    # 实现退出菜单事件
    def OnMenuClickEventExit(self, event):
        self.Destroy()